﻿using System;
using LocalOverride.Fiddler.Store;

namespace LocalOverride.Fiddler.UrlMapping
{
    public class MappingRegistryFactory
    {
        private readonly IMappingStore store;

        public MappingRegistryFactory(IMappingStore store)
        {
            this.store = store;
        }

        public MappingRegistry Create()
        {
            var overrideMapping = new MappingRegistry();
            foreach (var mappingEntry in store.Entries)
            {
                if (store.ValidatorFor(mappingEntry).Validate().IsValid)
                {
                    var uri = new Uri(mappingEntry.Url);
                    string filePath = mappingEntry.LocalPath;

                    if (mappingEntry.IsDirectory)
                    {
                        var fileExtensions = mappingEntry.FileExtensions;
                        overrideMapping.AddMapping(new DirectoryMapping(uri, filePath, fileExtensions, mappingEntry.DownloadLocalCopy, mappingEntry.DefaultFileName, new[]{"axd"}, new SpecialCaseMappingsProvider(mappingEntry)));
                    }
                    else
                    {
                        overrideMapping.AddMapping(new SingleFileMapping(uri, filePath));
                    }
                }
            }
            return overrideMapping;
        }
    }
}